package com.learn.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@RequestMapping("/thread")
@RestController
public class ThreadController {

    @Qualifier("dataExecutorService")
    @Autowired
    private ThreadPoolTaskExecutor executor;

    @GetMapping("/test")
    public Object testThread() throws IOException {
        List<String> stringList = new ArrayList<>();
        String str = "";

        // str = threadService.getString();

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println(Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(3);
                System.out.println("=======================");
                return UUID.randomUUID().toString();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return UUID.randomUUID().toString();
        }, executor);
        future.whenComplete((uuid, exception) -> {
            System.out.println(uuid);
            System.out.println(Thread.currentThread().getName());
        });

        System.out.println(11111);
        System.in.read();

        return str;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println(Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(3);

                System.out.println("=======================");
                return UUID.randomUUID().toString();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return UUID.randomUUID().toString();
        });
        future.whenComplete((uuid, exception) -> {
            System.out.println(uuid);
            System.out.println(Thread.currentThread().getName());
        });

        System.out.println(11111);
        System.in.read();

    }

}

